Skip to main content

Zero-Shot Classification

One of CLIP’s most powerful capabilities is zero-shot classification: the ability to classify images into categories the model has never been explicitly trained on. This is achieved by comparing image embeddings with text embeddings of potential class labels.

Core Concept

Instead of learning a fixed classifier head for specific categories, CLIP:
  1. Encodes the image into an embedding vector
  2. Encodes candidate text labels (e.g., “a photo of a dog”) into embedding vectors
  3. Computes similarity scores between the image and each text embedding
  4. Selects the highest scoring label as the prediction
Key Insight: Classification becomes a similarity search problem in the joint embedding space, not a traditional softmax over learned weights.

How It Works

Step 1: Prepare Text Prompts

Convert class names into descriptive text prompts using templates:
Why templates? Context matters! “a photo of a dog” provides more semantic information than just “dog”, leading to better embeddings.

Step 2: Build Zero-Shot Classifier Weights

From src/open_clip/zero_shot_classifier.py:21-68:
Key steps:
  1. Generate prompts for each class using multiple templates
  2. Encode all prompts to get text embeddings
  3. Average embeddings across templates for each class (ensemble)
  4. Normalize to unit length
  5. Transpose to shape [embed_dim, num_classes]

Step 3: Classify Images

From src/open_clip_train/zero_shot.py:17-42:
Classification process:
  1. Encode image → normalized embedding vector
  2. Matrix multiply with classifier weights: logits = image_features @ zeroshot_weights
  3. Scale by 100 (temperature scaling)
  4. Argmax to get predicted class

Temperature Scaling and Similarity Computation

Cosine Similarity

Since both image and text embeddings are L2-normalized, their dot product equals cosine similarity:
Values range from -1 (opposite) to +1 (identical).

Temperature Scaling

The scaling factor (100.0 in the example) controls prediction confidence:
  • Higher temperature → sharper probability distribution, more confident predictions
  • Lower temperature → softer distribution, less confident predictions
From the CLIP model (src/open_clip/model.py:274-298):
During training, logit_scale is learned. At inference:

Softmax Probabilities

To get class probabilities:

Real Example from Codebase

ImageNet Zero-Shot Evaluation

From src/open_clip_train/zero_shot.py:45-86:
What’s happening:
  1. Model has never seen ImageNet classification task during training
  2. Build classifier from 1000 ImageNet class names using 7 prompt templates
  3. Evaluate on ImageNet validation set
  4. Achieve competitive accuracy without task-specific fine-tuning!

OpenAI’s ImageNet Templates

Used in the original CLIP paper:
Multiple templates help capture diverse visual contexts.

Practical Usage Example

Custom Classification

Classify an image into custom categories:

Zero-Shot vs Fine-Tuning

Zero-Shot (No Fine-Tuning)

Advantages:
  • Works on any categories without training data
  • Instant deployment to new tasks
  • No overfitting to specific datasets
  • Leverages large-scale pretraining
Limitations:
  • Lower accuracy than fine-tuned models on specific tasks
  • Sensitive to prompt engineering
  • May struggle with fine-grained distinctions

With Fine-Tuning

Advantages:
  • Higher accuracy on target task
  • Adapts to specific visual distributions
  • Can learn task-specific features
Limitations:
  • Requires labeled training data
  • May lose zero-shot generalization
  • Risk of overfitting
For fine-tuning CLIP, see the WiSE-FT repository which implements robust fine-tuning techniques.

Advanced Techniques

Prompt Engineering

Better prompts → better performance:

Ensemble Multiple Templates

Averaging embeddings across templates improves robustness (already done in build_zero_shot_classifier).

Hierarchical Classification

For fine-grained tasks, use two-stage classification:
  1. Coarse categories: “bird”, “mammal”, “vehicle”
  2. Fine-grained: “golden retriever”, “labrador”, “poodle”

Performance Benchmarks

From the README, OpenCLIP models achieve strong zero-shot ImageNet accuracy: Without any ImageNet-specific training!

Key Takeaways

  1. Zero-shot = Similarity search: Classification as nearest neighbor in embedding space
  2. Prompts matter: “a photo of a dog” > “dog”
  3. Template ensembling: Average across multiple prompts for robustness
  4. Temperature scaling: Controls prediction sharpness
  5. No training data needed: Instant deployment to new categories
  6. Trade-off: Convenience vs accuracy (compared to fine-tuning)

Reference Files

  • src/open_clip/zero_shot_classifier.py - Classifier building logic
  • src/open_clip_train/zero_shot.py - Zero-shot evaluation during training
  • src/open_clip/zero_shot_metadata.py - ImageNet classnames and templates

CLIP Overview

Understanding the dual encoder architecture

Contrastive Learning

How CLIP learns aligned embeddings

Further Reading